package svc

import (
	"context"
	"group-buy/group_buy/internal/config"
	"group-buy/group_buy/internal/orm"
	"log"

	"github.com/ArtisanCloud/PowerWeChat/v3/src/miniProgram"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/option"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
	"xorm.io/xorm"
)

type ServiceContext struct {
	Config config.Config
	MiniApp *miniProgram.MiniProgram
	Engine  *xorm.Engine
	WxPay   *core.Client
}

func NewServiceContext(c config.Config) *ServiceContext {
	MiniProgramApp, err := miniProgram.NewMiniProgram(&miniProgram.UserConfig{
		AppID:     c.MiniApp.AppID,
		Secret:    c.MiniApp.Secret,
		HttpDebug: c.MiniApp.Debug,
		Log: miniProgram.Log{
			Level: "debug",
			File:  c.MiniApp.Log,
		},
		// 可选，不传默认走程序内存
		//Cache: kernel.NewRedisClient(&kernel.RedisOptions{
		//	Addr:     "127.0.0.1:6379",
		//	Password: "",
		//	DB:       0,
		//}),
	})
	if err != nil {
		log.Fatal("app init fail")
	}

	mchPrivateKey, err := utils.LoadPrivateKey(c.WxPay.MchPrivateKey)
	if err != nil {
		log.Fatal("load merchant private key error")
	}
	opts := []core.ClientOption{
		option.WithWechatPayAutoAuthCipher(c.WxPay.SpMchID, c.WxPay.MchCertificateSerialNumber, mchPrivateKey, c.WxPay.MchAPIv3Key),
	}
	client, err := core.NewClient(context.Background(), opts...)

	return &ServiceContext{
		Config:  c,
		MiniApp: MiniProgramApp,
		Engine:  orm.Init(c.Mysql.DataSource),
		WxPay:   client,
	}
}
